<template>
  <div ref="chartContainer" style="height: 100%"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { Pie } from '@antv/g2plot'

const props = defineProps({
  data: {
    type: Array,
    required: true,
    default: () => []
  }
})

const chartContainer = ref(null)
let piePlot = null

onMounted(() => {
  renderChart()
})

onBeforeUnmount(() => {
  if (piePlot) {
    piePlot.destroy()
  }
})

const renderChart = () => {
  if (!chartContainer.value) return

  piePlot = new Pie(chartContainer.value, {
    data: props.data,
    angleField: 'value',
    colorField: 'type',
    radius: 0.8,
    label: {
      type: 'spider',
      labelHeight: 28,
      content: '{name}\n{percentage}'
    },
    interactions: [{ type: 'element-active' }],
    legend: {
      position: 'bottom'
    },
    tooltip: {
      formatter: (datum) => {
        return { name: datum.type, value: `${datum.value}人 (${(datum.percent * 100).toFixed(2)}%)` }
      }
    }
  })

  piePlot.render()
}
</script>